import nodemailer from "nodemailer";
import {emailAccountConfig} from "@/common/email/email.account.config";
import {emailTemplateConfig} from "@/common/email/email.template.config";
//当前发送邮箱
let currentSendEmail = {auth: {user: {}}}
export const transporter = () => {
	// 生成 [n,m)，包含n但不包含m的正整数：  parseInt(Math.random()*(m-n)+n)
	// const randomNumber = parseInt(Math.random() * (8 - 0)); //0-7随机整数
	const __rand__ = Math.random();
	const section = 1 / emailAccountConfig.length; //每等分多少
	let initVal = 0; //初始值
	for (let i = 0; i <= emailAccountConfig.length; i++) {
		if (__rand__ > initVal && __rand__ < initVal + section) {
			currentSendEmail = emailAccountConfig[i]
		}
		initVal += section;
	}
	console.log("currentSendEmail", currentSendEmail)
	return nodemailer.createTransport({
		secureConnection: true, // 启动SSL
		port: 465, // 端口就是465
		...currentSendEmail
	})
}

const mailOptions = () => ({
	from: currentSendEmail.auth.user, // 发送者,与上面的user一致
	to: 'xxxx@xxx.com', // 接收者,可以同时发送多个,以逗号隔开
});

export function sendEmail(to, type, params) {
	console.log("to, type , params", to, type, params)
	const template = emailTemplateConfig[type](params)
	return new Promise((resolve, reject) => {
		transporter().sendMail({
			...mailOptions(),
			...template,
			to
		}, (err, info) => {
			if (err) {
				console.log('sendEmail', err);
				resolve(err)
				return;
			}
			resolve(template.returnValue)
			console.log('returnValue', template.returnValue);
		})
	})
}
